﻿using System;
using System.Collections.Generic;
using System.Linq;
using SW.Lite.BLL.Master;
using SW.Lite.Core.Authority;
using SW.Lite.Model.Master;

namespace SW.Lite.Core.Attributes
{
    /// <summary>
    /// Class ButtonAttribute.
    /// </summary>
    public class ButtonAttribute : MenuAttribute
    {
        /// <summary>
        /// Gets or sets the button code.
        /// </summary>
        /// <value>The button code.</value>
        public string ButtonCode { get; set; }

        /// <summary>
        /// Called when [action executing].
        /// </summary>
        /// <param name="filterContext">The filter context.</param>
        public override void OnActionExecuting(System.Web.Mvc.ActionExecutingContext filterContext)
        {
            base.OnActionExecuting(filterContext);
            if (String.IsNullOrEmpty(ButtonCode) || FinalRoles == null)
            {
                ReturnResult(filterContext);
                return;
            }

            var buttons = Button.GetButtonsByRoleIds(FinalRoles.Select(r => r.Id).ToArray());

            var bCodes = ButtonCode.Split(',');

            if (
                (from btn in buttons 
                 where bCodes.Contains(btn.Code) 
                 select Menu.Single(btn.MenuID)
                 ).Any(buttonMenuOwner => buttonMenuOwner.Code == MenuCode))
            {
                return;
            }

            ReturnResult(filterContext);
        }
    }
}
